import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog
from PyQt5.QtGui import QPixmap, QImage

from RyanUI import Ui_MainWindow
from machine_translation.translate import translate_text
from OCR.ocr.demo import recognize_text_from_image
from Fourier_Change.flybh import high_pass_filter, low_pass_filter, apply_fourier_transform
from tuxiangfenge.tuxiangfenge import Division_Merge_Segmented, region_growing
from jiucuo.examples.kenlm.demo import error_correction
from Smoothing_Sharpening.Smooth_Sharpen import Mean_Filtering, Gaussian_Filtering, Median_Filtering, Bilateral_Filtering, Laplacian_Operator, Unsharp_Masking
from Fourier_Change.Butterworth_Gauss import apply_butterworth_filter, apply_butterworth_highpass_filter, GLPF, GHPF


def convet2GrayQImage(img):
    height, width = img.shape
    bytes_per_line = width
    # img = img.astype(np.uint8)
    return QImage(img.data.tobytes(), width, height, bytes_per_line, QImage.Format_Grayscale8)


def convet2RGBQImage(img):
    height, width, channel = img.shape
    return QImage(img, width, height, width * channel, QImage.Format_RGB888)


class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)
        self.Filter_item.addItem('请选择方式')
        self.Filter_item.addItem('高通滤波')
        self.Filter_item.addItem('低通滤波')
        self.Filter_item.addItem('均值滤波')
        self.Filter_item.addItem('高斯滤波')
        self.Filter_item.addItem('中值滤波')
        self.Filter_item.addItem('双边滤波')
        self.Filter_item.addItem('拉普拉斯算子锐化')
        self.Filter_item.addItem('非锐化掩膜')
        self.Filter_item.addItem('巴特沃斯低通滤波')
        self.Filter_item.addItem('巴特沃斯高通滤波')
        self.Filter_item.addItem('高斯低通滤波')
        self.Filter_item.addItem('高斯高通滤波')
        self.Filter_Button.setEnabled(False)

        self.Fourier_item.addItem('请选择变换方式')
        self.Fourier_item.addItem('傅里叶变换')
        self.Fourier_item.addItem('反傅里叶变换')
        self.Fourier_Button.setEnabled(False)

        self.Execute_item.addItem('请选择方法')
        self.Execute_item.addItem('区域生长')
        self.Execute_item.addItem('图像分割')
        self.Execute_Button.setEnabled(False)

        # 初始化滤波滑块值
        self.Filter_num1.setMinimum(1)
        self.Filter_num1.setMaximum(239)
        self.Filter_num1.setValue(19)
        self.Filter_num1.valueChanged.connect(self.filter)

        self.Filter_num2.setMinimum(1)
        self.Filter_num2.setMaximum(239)
        self.Filter_num2.setValue(20)
        self.Filter_num2.valueChanged.connect(self.filter)

        self.Filter_num3.setMinimum(-10)
        self.Filter_num3.setMaximum(10)
        self.Filter_num3.setValue(1)
        self.Filter_num3.valueChanged.connect(self.filter)

        self.Filter_num4.setMinimum(-10)
        self.Filter_num4.setMaximum(10)
        self.Filter_num4.setValue(0)
        self.Filter_num4.valueChanged.connect(self.filter)

        # 初始化执行滑块值
        self.Area_X.setMinimum(0)
        self.Area_X.setMaximum(255)
        self.Area_X.setValue(20)
        self.Area_X.valueChanged.connect(self.execution)

        self.Area_Y.setMinimum(0)
        self.Area_Y.setMaximum(255)
        self.Area_Y.setValue(220)
        self.Area_Y.valueChanged.connect(self.execution)

        self.Area_Z.setMinimum(0)
        self.Area_Z.setMaximum(255)
        self.Area_Z.setValue(120)
        self.Area_Z.valueChanged.connect(self.execution)

        # 连接下拉框的当前索引变化事件到处理函数
        self.Filter_item.currentIndexChanged.connect(self.open_Filter)
        self.Fourier_item.currentIndexChanged.connect(self.open_Fourier)
        self.Execute_item.currentIndexChanged.connect(self.open_Execution)

        self.bind_slots()

    def execution(self):
        print("点击了 执行操作")
        selected_execution = self.Execute_item.currentText()    # 获取当前选中的滤波选项
        X = self.Area_X.value()  # 获取滑块1的值
        Y = self.Area_Y.value()  # 获取滑块2的值
        Z = self.Area_Z.value()  # 获取滑块3的值
        img = self.file_path
        if selected_execution == '区域生长':
            print(f"选择了 {selected_execution} 方法，区域: {X,Y} , 阈值：{Z}")
            result = Division_Merge_Segmented(img, X, Y)

        elif selected_execution == '图像分割':
            print(f"选择了 {selected_execution} 方法，灰度范围: {X,Y}")
            result = region_growing(X, Y, Z, img)

        outimg = convet2GrayQImage(result)
        self.Output_Img.setPixmap(QPixmap(outimg))

    def open_Execution(self):
        # 只在用户选择了实际的方法选项时启用执行操作按钮
        if self.Execute_item.currentIndex() > 0:
            self.Execute_Button.setEnabled(True)
        else:
            self.Execute_Button.setEnabled(False)

    def open_Filter(self):
        # 只在用户选择了实际的滤波选项时启用滤波按钮
        if self.Filter_item.currentIndex() > 0:
            self.Filter_Button.setEnabled(True)
        else:
            self.Filter_Button.setEnabled(False)

    def open_Fourier(self):
        # 只在用户选择了实际的傅里叶选项时启用傅里叶按钮
        if self.Fourier_item.currentIndex() > 0:
            self.Fourier_Button.setEnabled(True)
        else:
            self.Fourier_Button.setEnabled(False)

    def open_img(self):
        print("点击了打开图片")
        self.file_path = QFileDialog.getOpenFileName(
            self, directory="./", filter="*.jpg;*.png;*.jpeg")
        if self.file_path[0]:
            self.file_path = self.file_path[0]
            # print(self.file_path.shape)
            self.Origin_Img.setPixmap(QPixmap(self.file_path))

    def corrector(self):
        print("点击了文本纠错")
        text = self.text
        self.Trans_Cor_OutPut.setText(error_correction(text))

    def trans(self):
        print("点击了翻译")
        text = self.text
        self.Trans_Cor_OutPut.setText(translate_text(text))

    def ocr(self):
        print("点击了OCR")
        self.text = recognize_text_from_image(self.file_path)
        self.OCR_OutPut.setText(self.text)

    def filter(self):
        selected_filter = self.Filter_item.currentText()    # 获取当前选中的滤波选项
        filter_value1 = self.Filter_num1.value()  # 获取滑块1的值
        filter_value2 = self.Filter_num2.value()  # 获取滑块2的值
        filter_value3 = self.Filter_num3.value()  # 获取滑块3的值
        filter_value4 = self.Filter_num4.value()  # 获取滑块4的值
        print(f"选择了 {selected_filter} 方式")
        img = self.file_path
        if selected_filter == '高通滤波':
            print(f"阈值： {filter_value1}")
            result = high_pass_filter(filter_value1, img)
            Gray = True

        elif selected_filter == '低通滤波':
            print(f"阈值： {filter_value1}")
            result = low_pass_filter(filter_value1, img)
            Gray = True

        elif selected_filter == '均值滤波':
            if filter_value1 % 2 == 0:
                filter_value1 = filter_value1+1
            print(f"ksize: {filter_value1}")
            result = Mean_Filtering(img, ksize=filter_value1)
            Gray = False

        elif selected_filter == '高斯滤波':
            if filter_value1 % 2 == 0:
                filter_value1 = filter_value1+1
            print(f"ksize: {filter_value1}, sigmaX: {filter_value2}")
            result = Gaussian_Filtering(
                img, ksize=filter_value1, sigmaX=filter_value2)
            Gray = False

        elif selected_filter == '中值滤波':
            if filter_value1 % 2 == 0:
                filter_value1 = filter_value1+1
            print(f"ksize: {filter_value1}")
            result = Median_Filtering(img, ksize=filter_value1)
            Gray = False

        elif selected_filter == '双边滤波':
            if filter_value1 % 2 == 0:
                filter_value1 = filter_value1+1
            print(
                f"d: {filter_value1}, sigmaColor: {filter_value2}, sigmaSpace: {filter_value3}")
            result = Bilateral_Filtering(
                img, d=filter_value1, sigmaColor=filter_value2, sigmaSpace=filter_value3)
            Gray = False

        elif selected_filter == '拉普拉斯算子锐化':
            if filter_value1 % 2 == 0:
                filter_value1 = filter_value1+1
            print(
                f"ksize:{filter_value1}, scale:{filter_value2}, delta:{filter_value3}")
            result = Laplacian_Operator(
                img, ksize=filter_value1, scale=filter_value2, delta=filter_value3)
            Gray = True

        elif selected_filter == '非锐化掩膜':
            if filter_value1 % 2 == 0:
                filter_value1 = filter_value1+1
            print(
                f"ksize:{filter_value1}, sigmaX:{filter_value2}, img_weight:{filter_value3}, blurred_weight:{filter_value4}")
            result = Unsharp_Masking(img, ksize=filter_value1, sigmaX=filter_value2,
                                     img_weight=filter_value3, blurred_weight=filter_value4)
            Gray = False

        elif selected_filter == '巴特沃斯低通滤波':
            print(
                f"cutoff_frequency:{filter_value1}, filter_order:{filter_value2}")
            result = apply_butterworth_filter(
                img, cutoff_frequency=filter_value1, filter_order=filter_value2)
            Gray = True

        elif selected_filter == '巴特沃斯高通滤波':
            print(
                f"cutoff_frequency:{filter_value1}, filter_order:{filter_value2}")
            result = apply_butterworth_highpass_filter(
                img, cutoff_frequency=filter_value1, filter_order=filter_value2)
            Gray = True

        elif selected_filter == '高斯高通滤波':
            print(f"n:{filter_value1}, d0:{filter_value3}")
            result = GHPF(img, n=filter_value1, d0=filter_value3)
            Gray = True

        elif selected_filter == '高斯低通滤波':
            print(f"n:{filter_value1}, d0:{filter_value3}")
            result = GLPF(img, n=filter_value1, d0=filter_value3)
            Gray = True

        if Gray:
            outimg = convet2GrayQImage(result)
        else:
            outimg = convet2RGBQImage(result)
        self.Output_Img.setPixmap(QPixmap(outimg))

    def SaveResult(self):
        print("点击了保存图片")
        pixmap = self.Output_Img.pixmap()
        if pixmap:
            file_path, _ = QFileDialog.getSaveFileName(
                self, "保存图片", "", "Images (*.png *.xpm *.jpg *.jpeg)")
            if file_path:
                pixmap.save(file_path)

    def fourier(self):
        print("点击了 执行傅里叶变换")
        selected_fourier = self.Fourier_item.currentText()    # 获取当前选中的变换方法
        print(f"选择了 {selected_fourier} 方式")
        img = self.file_path
        if selected_fourier == '傅里叶变换':
            result, _ = apply_fourier_transform(img)

        elif selected_fourier == '反傅里叶变换':
            _, result = apply_fourier_transform(img)

        outimg = convet2GrayQImage(result)
        self.Output_Img.setPixmap(QPixmap(outimg))

    def img_cut(self):
        print("点击了 图像分割")
        img = self.file_path
        res = convet2RGBQImage(Division_Merge_Segmented(img))
        self.Output_Img.setPixmap(QPixmap(res))

    def bind_slots(self):  # 信号与槽绑定 识别鼠标点击信号
        self.InPut.clicked.connect(self.open_img)
        self.Translation.clicked.connect(self.trans)
        self.Filter_Button.clicked.connect(self.filter)
        self.Corrector.clicked.connect(self.corrector)
        self.Save_Img.clicked.connect(self.SaveResult)
        self.OCR_Push.clicked.connect(self.ocr)
        self.Fourier_Button.clicked.connect(self.fourier)
        self.Execute_Button.clicked.connect(self.execution)


if __name__ == "__main__":
    app = QApplication(sys.argv)

    window = MainWindow()
    window.show()

    app.exec()
